import compress from "./compress.js";
import {
	getTempKey
} from '@/api/upload';



export async function uploadfile(files, type) {
	var url = [];
	for (let i = 0; i < files.length; i++) {
		let item = files[i]
		let type = item.type.split('/')[0];
		let ext = item.name.split('.')[1];
		if (type == 'image') {
			compress.compressImg(item).then(res => {
				item = res
			})
		}
		await getTempKey({
			'type': type,
			'ext': ext
		}).then(res => {
			let data = {
				SecretId: res.data.credentials.tmpSecretId,
				SecretKey: res.data.credentials.tmpSecretKey,
				XCosSecurityToken: res.data.credentials.sessionToken,
				StartTime: res.data.startTime, // 时间戳，单位秒，如：1580000000
				ExpiredTime: res.data.expiredTime // 时间戳，单位秒，如：1580000900})
			}
			putFile(data,item, res.data);
			url.push(res.data.url + res.data.filepath);
		});
	}
	return url;
}


function putFile(data,filesObj, tempKey) {
	let url = '';
	var COS = require('cos-js-sdk-v5');
	var cos = new COS(data);
	cos.putObject({
			Bucket: tempKey.bucket,
			/* 必须 */
			Region: tempKey.region,
			/* 存储桶所在地域，必须字段 */
			Key: tempKey.filepath,
			/* 必须 */
			StorageClass: 'STANDARD',
			Body: filesObj, // 上传文件对象
			onProgress: progressData => {
				// console.log(JSON.stringify(progressData), "=+++")
			}
		},
		(err, data) => {
			
		}
	)


}

/* 获取本地路径 */
export function getObjectURL(file) {
	var url = null;
	if (window.createObjectURL != undefined) { // basic
		url = window.createObjectURL(file);
	} else if (window.URL != undefined) { // mozilla(firefox)
		url = window.URL.createObjectURL(file);
	} else if (window.webkitURL != undefined) { // webkit or chrome
		url = window.webkitURL.createObjectURL(file);
	}
	return url;
}
